<?php
// 修复路径问题 - 使用绝对路径
$adminDir = __DIR__;
$projectRoot = dirname($adminDir);

require_once $projectRoot . '/config/config.php';
require_once $projectRoot . '/includes/auth.php';
require_once $projectRoot . '/includes/database.php';

// session已由config/config.php统一管理，无需重复调用

// 检查登录状态
requireLogin();

// 简单的重定向函数
function redirect($url) {
    header("Location: " . $url);
    exit;
}

/**
 * 完全隔离的重置统计数据函数
 * 该函数不与主页面代码产生任何交互，确保只输出纯净的JSON
 */
function isolateResetStats($projectRoot) {
    // 1. 立即清空所有可能的输出缓冲
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    
    // 2. 禁用所有错误和警告显示
    error_reporting(0);
    ini_set('display_errors', 0);
    
    // 3. 检查是否是AJAX请求
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        // 4. 设置严格的JSON响应头
        header_remove(); // 移除所有已设置的头信息
        header('Content-Type: application/json; charset=utf-8');
        header('X-Content-Type-Options: nosniff');
        
        // 5. 准备重置后的统计数据结构 - 根据实际的stats.json文件结构
        $resetStats = [
            'total_visits' => 0,
            'today_visits' => 0,
            'last_visit_date' => '',
            'total_searches' => 0,
            'daily_stats' => [],
            'popular_links' => [],
            'search_keywords' => [],
            'last_reset_at' => date('Y-m-d H:i:s')
        ];
        
        // 6. 定义文件路径
        $statsFile = $projectRoot . '/data/stats.json';
        
        try {
            // 7. 尝试将数据写入文件
            $jsonData = json_encode($resetStats, JSON_UNESCAPED_UNICODE);
            
            if ($jsonData === false) {
                // JSON编码失败 - 使用静态JSON字符串
                echo '{"success":false,"message":"JSON编码错误"}';
            } else {
                // 8. 确保目录存在
                $dataDir = dirname($statsFile);
                if (!is_dir($dataDir)) {
                    mkdir($dataDir, 0755, true);
                }
                
                // 9. 写入文件
                if (file_put_contents($statsFile, $jsonData) !== false) {
                    echo '{"success":true,"message":"统计数据已成功重置"}';
                } else {
                    echo '{"success":false,"message":"无法写入统计数据文件"}';
                }
            }
        } catch (Exception $e) {
            // 异常情况 - 使用静态JSON字符串
            echo '{"success":false,"message":"重置过程中发生错误"}';
        }
        
        // 10. 确保脚本完全终止
        exit;
    }
    
    // 不是AJAX请求时直接退出
    exit;
}

// 初始化数据库
$db = new Database();

// 获取当前设置
$settings = $db->getSettings();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $csrfToken = $_POST['csrf_token'] ?? '';
    
    // 验证CSRF令牌
    if (!validateCsrfToken($csrfToken)) {
        $_SESSION['message'] = 'CSRF验证失败';
        $_SESSION['message_type'] = 'error';
    } else {
        switch ($action) {
            case 'update_password':
                $currentPassword = $_POST['current_password'] ?? '';
                $newPassword = $_POST['new_password'] ?? '';
                $confirmPassword = $_POST['confirm_password'] ?? '';
                
                if (!$db->validateAdminPassword($currentPassword)) {
                    $_SESSION['message'] = '当前密码不正确';
                    $_SESSION['message_type'] = 'error';
                } elseif (empty($newPassword) || strlen($newPassword) < 6) {
                    $_SESSION['message'] = '新密码至少需要6位字符';
                    $_SESSION['message_type'] = 'error';
                } elseif ($newPassword !== $confirmPassword) {
                    $_SESSION['message'] = '两次输入的密码不一致';
                    $_SESSION['message_type'] = 'error';
                } else {
                    if ($db->updateAdminPassword($newPassword)) {
                        $_SESSION['message'] = '密码修改成功';
                        $_SESSION['message_type'] = 'success';
                    } else {
                        $_SESSION['message'] = '密码修改失败';
                        $_SESSION['message_type'] = 'error';
                    }
                }
                break;
                
            case 'update_favicon':
                // 获取favicon_link值
                $faviconLink = sanitizeInput($_POST['favicon_link'] ?? '');
                
                // 准备更新数据
                $updateData = ['favicon_link' => $faviconLink];
                $successMessage = '';
                
                // 检查是否上传了新图标
                if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK) {
                    $uploadedFile = $_FILES['favicon'];
                    $fileInfo = pathinfo($uploadedFile['name']);
                    $allowedExtensions = ['ico', 'png', 'jpg', 'jpeg', 'gif', 'svg'];
                    
                    if (!in_array(strtolower($fileInfo['extension']), $allowedExtensions)) {
                        $_SESSION['message'] = '不支持的文件格式，支持的格式：' . implode(', ', $allowedExtensions);
                        $_SESSION['message_type'] = 'error';
                    } elseif ($uploadedFile['size'] > 1024 * 1024) { // 1MB limit
                        $_SESSION['message'] = '文件大小不能超过1MB';
                        $_SESSION['message_type'] = 'error';
                    } else {
                        // 获取当前favicon路径，用于删除旧文件
                        $currentSettings = $db->getSettings();
                        $currentFaviconPath = $currentSettings['favicon_path'] ?? 'assets/images/favicon.ico';
                        $currentFilePath = BASE_PATH . '/' . $currentFaviconPath;
                        
                        // 采用覆盖方式，保持文件名为favicon.ext
                        $newFileName = 'favicon.' . $fileInfo['extension'];
                        $uploadPath = BASE_PATH . '/assets/images/' . $newFileName;
                        
                        // 如果新文件扩展名不同，删除旧的favicon文件
                        if (file_exists($currentFilePath) && $currentFilePath !== $uploadPath) {
                            unlink($currentFilePath);
                        }
                        
                        if (move_uploaded_file($uploadedFile['tmp_name'], $uploadPath)) {
                            $updateData['favicon_path'] = 'assets/images/' . $newFileName;
                            $successMessage = '图标更新';
                        } else {
                            $_SESSION['message'] = '图标上传失败';
                            $_SESSION['message_type'] = 'error';
                        }
                    }
                } else if ($_FILES['favicon']['error'] === UPLOAD_ERR_NO_FILE) {
                    // 没有上传新图标，只更新链接
                    $successMessage = '链接设置';
                }
                
                // 保存更新
                if (!isset($_SESSION['message']) && $db->updateSiteInfo($updateData)) {
                    $_SESSION['message'] = '网站图标设置保存成功';
                    $_SESSION['message_type'] = 'success';
                } else if (!isset($_SESSION['message'])) {
                    $_SESSION['message'] = '网站图标设置保存失败';
                    $_SESSION['message_type'] = 'error';
                }
                break;
                
            case 'update_site_info':
                $siteTitle = sanitizeInput($_POST['site_title'] ?? '');
                $siteDescription = sanitizeInput($_POST['site_description'] ?? '');
                $siteKeywords = sanitizeInput($_POST['site_keywords'] ?? '');
                
                if (empty($siteTitle)) {
                    $_SESSION['message'] = '网站标题不能为空';
                    $_SESSION['message_type'] = 'error';
                } else {
                    $updateData = [
                        'site_title' => $siteTitle,
                        'site_description' => $siteDescription,
                        'site_keywords' => $siteKeywords
                    ];
                    
                    if ($db->updateSiteInfo($updateData)) {
                        $_SESSION['message'] = '网站信息更新成功';
                        $_SESSION['message_type'] = 'success';
                    } else {
                        $_SESSION['message'] = '网站信息更新失败';
                        $_SESSION['message_type'] = 'error';
                    }
                }
                break;
                
            case 'update_footer_info':
                $footerCopyright = sanitizeInput($_POST['footer_copyright'] ?? '');
                $footerIcpNumber = sanitizeInput($_POST['footer_icp_number'] ?? '');
                $footerBeianNumber = sanitizeInput($_POST['footer_beian_number'] ?? '');
                $footerOtherInfo = sanitizeInput($_POST['footer_other_info'] ?? '');
                
                $updateData = [
                    'footer_copyright' => $footerCopyright,
                    'footer_icp_number' => $footerIcpNumber,
                    'footer_beian_number' => $footerBeianNumber,
                    'footer_other_info' => $footerOtherInfo
                ];
                
                if ($db->updateSiteInfo($updateData)) {
                    $_SESSION['message'] = '底部信息更新成功';
                    $_SESSION['message_type'] = 'success';
                } else {
                    $_SESSION['message'] = '底部信息更新失败';
                    $_SESSION['message_type'] = 'error';
                }
                break;
                
            case 'reset_stats':
                // 隔离执行重置统计数据功能
                // 完全绕过主脚本，直接执行重置逻辑并返回JSON
                isolateResetStats($projectRoot);
                break;
                
            case 'update_footer_script':
                $footerScriptCode = sanitizeScriptCode($_POST['footer_script_code'] ?? '');
                
                $updateData = [
                    'footer_script_code' => $footerScriptCode
                ];
                
                if ($db->updateSiteInfo($updateData)) {
                    $_SESSION['message'] = '底部脚本代码更新成功';
                    $_SESSION['message_type'] = 'success';
                } else {
                    $_SESSION['message'] = '底部脚本代码更新失败';
                    $_SESSION['message_type'] = 'error';
                }
                break;
        }
    }
    redirect(getUrl('admin/settings'));
}

// 获取并清除消息
$message = $_SESSION['message'] ?? '';
$messageType = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

// 生成CSRF令牌
$csrfToken = generateCsrfToken();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - <?php echo $settings['site_title'] ?? SITE_TITLE; ?></title>
    
    <!-- 样式文件 -->
    <link rel="stylesheet" href="<?php echo asset('css/admin.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/fontawesome/all.min.css'); ?>">
    
    <!-- 网站图标 -->
    <link rel="icon" type="image/x-icon" href="<?php echo getUrl($settings['favicon_path'] ?? 'assets/images/favicon.ico'); ?>">
</head>
<body class="admin-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <i class="fas fa-compass"></i>
                <h2><?php echo $settings['site_title'] ?? SITE_TITLE; ?></h2>
            </div>
        </div>
        
        <nav class="sidebar-nav">
            <ul>
                <li>
                    <a href="<?php echo getUrl('admin/'); ?>">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表盘</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/navigations'); ?>">
                        <i class="fas fa-link"></i>
                        <span>导航管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/categories'); ?>">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/tags'); ?>">
                        <i class="fas fa-tags"></i>
                        <span>标签管理</span>
                    </a>
                </li>
                <li class="active">
                    <a href="<?php echo getUrl('admin/settings'); ?>">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl(); ?>" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                        <span>访问前台</span>
                    </a>
                </li>
            </ul>
        </nav>
        
        <div class="sidebar-footer">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span><?php echo $_SESSION['admin_username'] ?? 'Admin'; ?></span>
            </div>
            <a href="<?php echo getUrl('admin/?action=logout'); ?>" class="logout-btn" title="退出登录">
                <i class="fas fa-sign-out-alt"></i>
            </a>
        </div>
    </aside>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
        <!-- 顶部栏 -->
        <header class="content-header">
            <div class="header-left">
                <h1><i class="fas fa-cog"></i> 系统设置</h1>
                <p>管理系统的基本设置和安全配置</p>
            </div>
        </header>
        
        <!-- 消息提示 -->
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <!-- 设置内容 -->
        <div class="settings-container">
            <!-- 网站信息设置 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-globe"></i> 网站信息</h2>
                    <p>配置网站的基本信息</p>
                </div>
                
                <form method="POST" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="update_site_info">
                    
                    <div class="form-group">
                        <label for="site_title">网站标题</label>
                        <input type="text" id="site_title" name="site_title" 
                               value="<?php echo htmlspecialchars($settings['site_title'] ?? SITE_TITLE); ?>" 
                               required>
                        <small>在浏览器标题栏和页面标题中显示</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="site_description">网站描述</label>
                        <textarea id="site_description" name="site_description" rows="3"><?php echo htmlspecialchars($settings['site_description'] ?? SITE_DESCRIPTION); ?></textarea>
                        <small>用于搜索引擎优化和页面描述</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="site_keywords">网站关键词</label>
                        <input type="text" id="site_keywords" name="site_keywords" 
                               value="<?php echo htmlspecialchars($settings['site_keywords'] ?? SITE_KEYWORDS); ?>" 
                               placeholder="导航,网址导航,Apple风格,毛玻璃">
                        <small>用于SEO优化，多个关键词请用英文逗号分隔</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存网站信息
                    </button>
                </form>
            </section>
            
            <!-- 底部信息设置 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-copyright"></i> 底部信息</h2>
                    <p>配置网站底部显示的版权信息和备案号</p>
                </div>
                
                <form method="POST" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="update_footer_info">
                    
                    <div class="form-group">
                        <label for="footer_copyright">版权信息</label>
                        <input type="text" id="footer_copyright" name="footer_copyright" 
                               value="<?php echo htmlspecialchars($settings['footer_copyright'] ?? ''); ?>" 
                               placeholder="例如：© 2023 网站名称. 保留所有权利">
                        <small>显示在网站底部的版权信息</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="footer_icp_number">ICP备案号</label>
                        <input type="text" id="footer_icp_number" name="footer_icp_number" 
                               value="<?php echo htmlspecialchars($settings['footer_icp_number'] ?? ''); ?>" 
                               placeholder="例如：京ICP备12345678号">
                        <small>网站的ICP备案号</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="footer_beian_number">公安备案号</label>
                        <input type="text" id="footer_beian_number" name="footer_beian_number" 
                               value="<?php echo htmlspecialchars($settings['footer_beian_number'] ?? ''); ?>" 
                               placeholder="例如：京公网安备12345678号">
                        <small>网站的公安备案号</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="footer_other_info">其他信息</label>
                        <input type="text" id="footer_other_info" name="footer_other_info" 
                               value="<?php echo htmlspecialchars($settings['footer_other_info'] ?? ''); ?>" 
                               placeholder="例如：由XXX技术支持">
                        <small>显示在网站底部的其他信息</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存底部信息
                    </button>
                </form>
            </section>
            
            <!-- 底部脚本代码设置 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-code"></i> 底部脚本代码</h2>
                    <p>在网站底部添加自定义JavaScript代码（如统计代码、分析代码等）</p>
                </div>
                
                <form method="POST" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="update_footer_script">
                    
                    <div class="form-group">
                        <label for="footer_script_code">JavaScript代码</label>
                        <textarea id="footer_script_code" name="footer_script_code" rows="8" placeholder="例如：\n&lt;script&gt;\nconsole.log('Hello World');\n&lt;/script&gt;"><?php echo $settings['footer_script_code'] ?? ''; ?></textarea>
                        <small>将在网站底部HTML结束前添加的JavaScript代码，支持完整的script标签</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存脚本代码
                    </button>
                </form>
            </section>
            

            
            <!-- 密码修改 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-key"></i> 修改登录密码</h2>
                    <p>为了安全，请定期更换登录密码</p>
                </div>
                
                <form method="POST" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="update_password">
                    
                    <div class="form-group">
                        <label for="current_password">当前密码</label>
                        <input type="password" id="current_password" name="current_password" required>
                        <small>请输入当前登录密码进行验证</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="new_password">新密码</label>
                        <input type="password" id="new_password" name="new_password" required minlength="6">
                        <small>密码长度至少6位字符</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">确认新密码</label>
                        <input type="password" id="confirm_password" name="confirm_password" required minlength="6">
                        <small>请再次输入新密码进行确认</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-lock"></i> 修改密码
                    </button>
                </form>
            </section>
            
            <!-- Favicon 设置 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-image"></i> 网站图标 (Favicon)</h2>
                    <p>上传自定义的网站图标，并设置点击图标时跳转到的链接</p>
                </div>
                
                <div class="favicon-preview">
                    <div class="current-favicon">
                        <h4>当前图标</h4>
                        <img src="<?php echo getUrl($settings['favicon_path'] ?? 'assets/images/favicon.ico'); ?>" 
                             alt="Current Favicon" width="32" height="32">
                        <p><?php echo $settings['favicon_path'] ?? 'assets/images/favicon.ico'; ?></p>
                        <?php if (!empty($settings['favicon_link'])): ?>
                            <p>图标链接：<a href="<?php echo htmlspecialchars($settings['favicon_link']); ?>" target="_blank"><?php echo htmlspecialchars($settings['favicon_link']); ?></a></p>
                        <?php endif; ?>
                    </div>
                </div>
                
                <form method="POST" enctype="multipart/form-data" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="update_favicon">
                    
                    <div class="form-group">
                        <label for="favicon">选择新图标</label>
                        <input type="file" id="favicon" name="favicon" 
                               accept=".ico,.png,.jpg,.jpeg,.gif,.svg">
                        <small>支持格式：ICO, PNG, JPG, JPEG, GIF, SVG | 建议尺寸：16x16 或 32x32 像素 | 最大 1MB（留空表示不更新图标）</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="favicon_link">图标链接</label>
                        <input type="url" id="favicon_link" name="favicon_link" 
                               value="<?php echo htmlspecialchars($settings['favicon_link'] ?? ''); ?>" 
                               placeholder="例如：https://www.example.com">
                        <small>点击网站图标时跳转到的链接，留空表示不设置链接</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存设置
                    </button>
                </form>
            </section>
            
            <!-- 系统信息 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-info-circle"></i> 系统信息</h2>
                    <p>查看当前系统的配置信息</p>
                </div>
                
                <div class="system-info">
                    <div class="info-item">
                        <label>PHP 版本</label>
                        <span><?php echo PHP_VERSION; ?></span>
                    </div>
                    <div class="info-item">
                        <label>服务器时间</label>
                        <span><?php echo date('Y-m-d H:i:s'); ?></span>
                    </div>
                    <div class="info-item">
                        <label>数据目录</label>
                        <span><?php echo DATA_DIR; ?></span>
                    </div>
                    <div class="info-item">
                        <label>上传目录</label>
                        <span><?php echo UPLOAD_DIR; ?></span>
                    </div>
                    <div class="info-item">
                        <label>最后更新</label>
                        <span><?php echo $settings['updated_at'] ?? '未知'; ?></span>
                    </div>
                </div>
            </section>
            <!-- 统计管理 -->
            <section class="settings-section">
                <div class="section-header">
                    <h2><i class="fas fa-chart-line"></i> 统计管理</h2>
                    <p>管理系统的统计数据</p>
                </div>
                
                <div class="system-info">
                    <div class="alert alert-warning">
                        <p class="mb-0"><i class="fas fa-exclamation-triangle mr-2"></i>注意：重置统计将清除所有访问量和搜索记录，操作不可恢复！</p>
                    </div>
                    <div class="mt-4">
                        <button id="reset-stats-btn" class="btn btn-danger">
                            <i class="fas fa-redo-alt mr-2"></i>重置统计数据
                        </button>
                    </div>
                </div>
            </section>
            
        </div>
    </main>
    
    <!-- JavaScript -->
    <script src="<?php echo asset('js/admin.js'); ?>"></script>
    <script>
        // 密码确认验证
        document.getElementById('confirm_password').addEventListener('input', function() {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = this.value;
            
            if (newPassword !== confirmPassword) {
                this.setCustomValidity('两次输入的密码不一致');
            } else {
                this.setCustomValidity('');
            }
        });
        
        // 文件选择预览
        document.getElementById('favicon').addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    // 在这里可以添加预览功能
                    console.log('文件已选择:', file.name);
                };
                reader.readAsDataURL(file);
            }
        });
        
        // 重置统计数据
        function resetStats() {
            const resetBtn = document.getElementById('reset-stats-btn');
            
            // 使用AdminJS.confirmAction替代原生confirm
            AdminJS.confirmAction('确定要重置所有统计数据吗？此操作不可恢复！', function() {
                // 禁用按钮防止重复点击
                resetBtn.disabled = true;
                resetBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>重置中...';
                
                // 获取CSRF令牌
                const csrfToken = '<?php echo $csrfToken; ?>';
                
                fetch('reset_stats.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: 'csrf_token=' + encodeURIComponent(csrfToken)
                })
                .then(response => {
                    // 先检查响应状态
                    if (!response.ok) {
                        throw new Error('服务器响应错误: ' + response.status);
                    }
                    // 先获取原始文本，然后尝试解析JSON
                    return response.text().then(text => {
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            console.error('JSON解析错误:', e);
                            console.log('原始响应:', text);
                            // 如果解析失败，抛出包含原始文本的错误
                            throw new Error('JSON解析错误: ' + text.substring(0, 100) + '...');
                        }
                    });
                })
                .then(data => {
                    // 恢复按钮状态
                    resetBtn.disabled = false;
                    resetBtn.innerHTML = '<i class="fas fa-redo-alt mr-2"></i>重置统计数据';
                    
                    if (data.success) {
                        AdminJS.showAlert('统计数据已成功重置！', 'success');
                        // 刷新页面以更新统计显示
                        location.reload();
                    } else {
                        AdminJS.showAlert('重置统计数据失败：' + (data.message || '未知错误'), 'error');
                    }
                })
                .catch(error => {
                    // 恢复按钮状态
                    resetBtn.disabled = false;
                    resetBtn.innerHTML = '<i class="fas fa-redo-alt mr-2"></i>重置统计数据';
                    
                    console.error('重置统计数据时发生错误:', error);
                    AdminJS.showAlert('重置统计数据失败：' + (error.message || '未知错误'), 'error');
                });
            });
        }
        
        // 绑定重置统计按钮事件
        if (document.getElementById('reset-stats-btn')) {
            document.getElementById('reset-stats-btn').addEventListener('click', resetStats);
        }
    </script>
</body>
</html>